<template>
  <el-container >
    <el-header>
      <el-row>
        <el-col :span="1.5">
          <el-button @click="addUser=true,select=null" icon="el-icon-circle-plus-outline" type="primary">新增用户</el-button>&nbsp;
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-plus" @click="deleteByList">批量删除</el-button>&nbsp;
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" icon="el-icon-download" @click="downloadCSV">导出CSV</el-button>&nbsp;
        </el-col>
        <el-col :span="3">
        <el-upload
                        ref="upload"
                        class="upload-demo"
                        accept=".csv"
                        :on-change="uploadFile"
                        :auto-upload="false"
                        :before-upload="beforeUpload"
                        :file-list="fileList">
     <el-button size="large" type="primary" icon="el-icon-upload2" >导入CSV</el-button>
                </el-upload>
        </el-col>
      <el-col span="12">
        <el-col span="12" style="margin-right: 3px">
          <el-input v-model="searchText" @keyup.enter.native="search" placeholder="搜搜看">
            <i slot="suffix" class="el-icon-search" @click="search"></i>
          </el-input>
        </el-col>
      </el-col>
      </el-row>

    </el-header>
    <el-main>
      <el-table border lazy
                ref="multipleTable"
                :data="userDatas"
                style="width: 100%"
                @selection-change="addCheck">
        <el-table-column type="selection" width="39"></el-table-column>
        <el-table-column
            property="id"
            label="id"
            sortable
            width="250">
          <template slot-scope="scope">
            {{scope.row.id}}
          </template>
        </el-table-column>
        <el-table-column
            property="userName"
            label="用户昵称"
            width="250">
        </el-table-column>
        <el-table-column
            property="userRole"
            label="角色"
            width="250">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.userRole=='admin'">{{roles[scope.row.userRole]}}</el-tag>
            <el-tag type="warning" v-else-if="scope.row.userRole=='auditor'">{{roles[scope.row.userRole]}}</el-tag>
            <el-tag type="success" v-else-if="scope.row.userRole=='expert'">{{roles[scope.row.userRole]}}</el-tag>
            <el-tag v-else-if="scope.row.userRole=='user'">{{roles[scope.row.userRole]}}</el-tag>
            <el-tag type="info" v-else>{{roles[scope.row.userRole]}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            property="createdTime"
            label="注册日期"
            sortable
            width="250">
          <template slot-scope="scope">
            {{new Date(scope.row.createdTime).toLocaleString()}}
          </template>
        </el-table-column>
        <el-table-column
            property="updateTime"
            label="最近修改日期"
            sortable
            width="199">
          <template slot-scope="scope">
            {{new Date(scope.row.updateTime).toLocaleString()}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
     <el-button type="primary"
                       size="mini"
                       @click="edit=true,select=scope.row">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="  userQureyPageBody.current"
          :page-size.sync="  userQureyPageBody.pageSize"
          :page-sizes="[5, 10, 15, 20,25]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="this.total">
      </el-pagination>
    </el-footer>
    <el-dialog :visible.sync="edit" title="编辑用户">
      <user-message-box :key="new Date().getTime()"></user-message-box>
    </el-dialog>
    <el-dialog :visible.sync="addUser" title="新增用户">
      <user-message-box ></user-message-box>
    </el-dialog>
  </el-container>

</template>

<script>
import UserMessageBox from "@/components/userComponents/userMessageBox";
import {DeleteRequestBody} from "@/core/request/model/common/deleteRequestBody";
// import {docAPI} from "@/core/request/api/DocApi";
import {globalValue} from "@/core/config/globalConfig";
import {userQureyRequestBody} from "@/core/request/model/user/UserQueryRequestBody";
import {userApi} from "@/core/request/api/UserApi";
import row from "view-ui-plus/src/components/row";

export default {
  name: "userPage",
    computed: {
        row() {
            return row
        }
    },
  components: {UserMessageBox},
  data(){
    return{
      select:null,
      edit:false,
      user:sessionStorage.getItem('loginStatus'),
      total:0,
      userDatas:[],
      searchText:null,
      addUser:false,
      userQureyPageBody:new userQureyRequestBody(),
      reqBody:{
        userVoList:[]
      },
        ids:[],
        fileList:[],
      roles:this.$store.state.user.roles,
      genders:this.$store.state.user.genders
    }
  },
  methods:{
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    gotoGarbage(){
      this.$router.push('/userGarbagePage')
    },
    delete(data){
      var deleteRequestBody = new DeleteRequestBody();
      deleteRequestBody.id=data.id
      this.axios.post(userApi.deleteUser,deleteRequestBody)
          .then(res=>{
            if (!res.data.code){
              this.$message.success(res.data.message)
              this.userDatas.splice(this.userDatas.indexOf(data),1)
            }

          })
    },
    handleDelete(data){
      if (data.userRole=='admin'){
        this.$confirm('用户 Id='+data.id+' '+data.userAccount+'('+data.userName+') 为管理员账户, 是否继续删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(()=>{
          this.delete(data);
        })
            .catch(()=>{
            })
      }
      else{
        this.delete(data);
      }
    },
    deleteByList(){
      for(var i=0;i<this.reqBody.userVoList.length;i++)
        this.handleDelete(this.reqBody.userVoList[i]);

    },
      beforeUpload(file){
          const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
          const whiteList = ["csv"]
          if (whiteList.indexOf(fileSuffix) === -1) {
              this.$message.error('上传文件只能是csv格式');
              return false;
          }
      },
      async uploadFile(file){
          const formData = new FormData()
          formData.append('file',file.raw)
          // console.log(file.raw)
          await userApi.importUser(formData).then(res=>{
              console.log(res)
              if(res.data.code!==0) return this.$message.error('导入失败')
              this.$message.success('导入成功')
              this.$refs.upload.clearFiles()
          })
      },
      // beforeRemove(){
      //
      // },
    downloadCSV(){
        if(this.ids.length==0){
            this.$message.warning('请勾选要导出的数据项，在id项前面打勾')
        }
        else{
            userApi.exportUser({ids:this.ids}).then(res=>{
                // console.log(res)
                if(res.status==200){
                    globalValue.downloadFn(res.data)
                    this.$message.success('导出成功')
                }else {
                    this.$message.error(('导出CSV发生错误'))
                }
            })
        }
    },
    addCheck(selection){
        this.ids=selection.map(item=>item.id)
        // console.log(this.ids)
    },
    handleCurrentChange(val){
      this.userQureyPageBody.current=val
      this.send()
    },
    handleSizeChange(val){
      this.userQureyPageBody.pageSize=val;
      this.send()
    },
    search(){

    },
    send(){
      this.axios.post(userApi.getUserslistPage,this.userQureyPageBody
      )
          .then(res=>{
            if (!res.data.code){
                // console.log(res)
                this.total=parseInt(res.data.data.total)
               this.userDatas=res.data.data.records
                // console.log(res.data.data.records)
            }
          })
    },
  },
  mounted() {
    this.userQureyPageBody.sortField='createdTime'
    this.send()
  }
}
</script>

<style scoped>
.el-icon-search{
  border-radius: 3px;
  padding:8px;
  margin-top: 2px;
  margin-right: -2px;
  font-size: 20px
}
.el-icon-search:hover{
  background-color: #f1f1f1;
}
.el-tag--tags{
  background-color: #0000005e;
  border-color: rgba(166, 97, 97, 0.12);
  height: 32px;
  padding: 0 10px;
  line-height: 30px;
  font-size: 12px;
  color: #ffffffb0;
  border-width: 1px;
  border-style: solid;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
}
.el-upload__tip{
    display: inline;
margin-left: 8px;
}
</style>
